<?php
/**
 * ClassName: CardRechargeService
 * Description:
 * @Author 周昌
 * @Create 2024/1/17 9:36
 */

namespace service\admin;


use libs\Tool;
use model\CardRechargeModel;
use service\BaseService;
use think\Db;

class CardRechargeService extends BaseService
{
    protected static $model = 'model\CardRechargeModel';

    //分段消费
    public static function consume($card_id, $money)
    {
        $list = self::$model::getList(['card_id' => $card_id], 'id,card_id,money,gift_money', 'id asc');
        $seed_money = 0;//充值本金
        $gift_money = 0;//充值赠送
        $del_ids = [];
        foreach ($list as $k=>&$v){
            if ($money>$v['money']){
                $seed_money+=$v['money'];
                $money-=$v['money'];
                $v['money']=0;
                if($money<=$v['gift_money']){
                    $gift_money+=$money;
                    $v['gift_money']-=$money;
                    break;
                }else{
                    $gift_money+=$v['gift_money'];
                     $money-=$v['gift_money'];
                    $v['gift_money']=0;
                }

            }else{
                $seed_money+=$money;
                $v['money']-=$money;
                break;
            }
            //记录需要删除的，更新只是减少的
            if($v['money']==0&&$v['gift_money']==0){
                $del_ids[]=$v['id'];
                unset($list[$k]);
            }

        }
       Db::startTrans();
        try {
            if(!empty($del_ids)){
                $del_res=self::$model::delInfo([['id','in',$del_ids]]);
                if(!$del_res){
                    Db::rollback();
                    return Tool::Error('删除分段消费记录失败');
                }
            }
            //更新剩下的
            $card_recharge_model=new CardRechargeModel();
            $update_res=$card_recharge_model->saveAll($list);
            if($update_res===false){
                Db::rollback();
                return Tool::Error('更新分段消费记录失败');
            }
            Db::commit();
            return Tool::Success('成功',['seed_money'=>$seed_money,'gift_money'=>$gift_money]);
        }catch (\Exception $exception){
            Db::rollback();
            return Tool::Error($exception->getMessage());
        }



    }
    //根据card_id 获取本金总金额+赠送总金额
    public static function getMoney($card_id)
    {
        return self::$model::where('card_id','in',$card_id)->group('card_id')
            ->column('sum(money) as recharge_money,sum(gift_money) as gift_money','card_id');
    }

}